//
//  NewMobileVerifyViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/4.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "NewMobileVerifyViewController.h"

#import "ACMacros.h"
#import "HttpServer.h"
#import "User.h"
#import "Utility.h"
#import "Constants.h"

#import "AppDrawer.h"

#import <TSMessages/TSMessageView.h>
#import <MobClick.h>

@interface NewMobileVerifyViewController () <UITextFieldDelegate>

@end

@implementation NewMobileVerifyViewController {
    BOOL isMobileLegal;
    BOOL isVcodeLegal;
    BOOL isRequired;
    
    NSTimer *timer;
    NSInteger timeCount;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureNavigationBar];
    [self configureTextViews];
    [self configureTapGestures];
    [self configureButton];

    // Do any additional setup after loading the view from its nib.
}
-(void)viewWillAppear:(BOOL)animated
{
    [MobClick beginLogPageView:@"新手机号验证页"];//("PageOne"为页面名称，可自定义)

}
-(void)viewWillDisappear:(BOOL)animated
{
    [MobClick endLogPageView:@"新手机号验证页"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)configureNavigationBar {
    self.title = @"更改手机号";
    self.navigationItem.hidesBackButton = true;
    UIImage *backImage = [[UIImage imageNamed:@"back-18-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithImage:backImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToPopBack)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
}

- (void)configureTextViews {
    [self.mobileTextField setDelegate:self];
    [self.vcodeTextField setDelegate:self];
}

- (void)configureTapGestures {
    UITapGestureRecognizer *tapCancelInput = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(canelInput)];
    [self.view addGestureRecognizer:tapCancelInput];
}

- (void)configureButton {
    [self.vcodeButton setUserInteractionEnabled:false];
    [self.vcodeButton addTarget:self action:@selector(clickToGetVcode) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - Triggering Methods
- (void)clickToPopBack {
    [self.navigationController popViewControllerAnimated:true];
}

- (void)clickToGetVcode {
    timeCount = 59;
    [self.vcodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.vcodeButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCount) userInfo:nil repeats:YES];
    [self verifyCodeRequest];
}

//- (IBAction)clickToLogin:(UIButton *)sender {
//    if (isRequired) {
//        [self presentViewController:[AppDrawer sharedDrawer] animated:true completion:^{
//        }];
//    } else {
//        NewRequirementViewController *newRequirementVC = [[NewRequirementViewController alloc]initWithNibName:@"NewRequirementViewController" bundle:nil];
//        [self presentViewController:newRequirementVC animated:true completion:^{
//        }];
//    }
//}


- (void)timerCount {
    self.vcodeButton.userInteractionEnabled = false;
    NSString *buttonTitle = [NSString stringWithFormat:@"%ld秒后重发",(long)timeCount];
    [self.vcodeButton setTitle:buttonTitle forState:UIControlStateNormal];
    timeCount--;
    if (timeCount <= 0) {
        [timer invalidate];
        self.vcodeButton.userInteractionEnabled = true;
        [self.vcodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}


#pragma mark - Text field delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIView animateWithDuration:0.2 animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [self.view setFrame:CGRectMake(0, - 30, Main_Screen_Width, Main_Screen_Height)];
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView animateWithDuration:0.2 animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [self.view setFrame:CGRectMake(0, 64, Main_Screen_Width, Main_Screen_Height)];
    }];
    if ([textField isEqual:self.mobileTextField]) {
        if ([self isValidateTelWithTel:textField.text]) {
            NSLog(@"legal");
        } else {
            [TSMessage showNotificationInViewController:self title:@"手机号码不合法!" subtitle:@"请输入正确的手机号码" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *value = textField.text;
    value = [NSString stringWithFormat:@"%@%@",value, string];
    if (value.length == 11 && textField.text.length == 10) {
        if ([self isValidateTelWithTel:value]) {
            [self.vcodeButton setUserInteractionEnabled:true];
            [self.vcodeButton setBackgroundColor:RGBACOLOR(255, 118, 108, 1)];
        } else {
            [self.vcodeButton setUserInteractionEnabled:false];
            [self.vcodeButton setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
        }
    } else {
        [self.vcodeButton setUserInteractionEnabled:false];
        [self.vcodeButton setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    }
    return true;
}


- (void)canelInput {
    [self.mobileTextField resignFirstResponder];
    [self.vcodeTextField resignFirstResponder];
}

-(BOOL)isValidateTelWithTel:(NSString*)tel
{
    NSString *patternTel = @"^1[3,4,5,7,8][0-9]{9}$";
    NSError *err = nil;
    NSRegularExpression *TelExp = [NSRegularExpression regularExpressionWithPattern:patternTel options:NSRegularExpressionCaseInsensitive error:&err];
    NSTextCheckingResult *isMatchTel = [TelExp firstMatchInString:tel options:0 range:NSMakeRange(0, [tel length])];
    if (isMatchTel)
    {
        isMobileLegal = true;
        NSLog(@"手机号码合法");
    }
    else
    {
        isMobileLegal = false;
        NSLog(@"手机号码不合法");
    }
    return isMobileLegal;
}

#pragma mark - Network methods
- (void)verifyCodeRequest {
    [HttpServer postToGetVcodeWithMobile:self.mobileTextField.text WithSuccessBlock:^(NSDictionary *successDic) {
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
    }];
}

- (IBAction)clickToLogin:(UIButton *)sender {
    [HttpServer postToLoginWithMobile:self.mobileTextField.text Vcode:self.vcodeTextField.text WithSuccessBlock:^(NSDictionary *successDic) {
        if ([[successDic allKeys]containsObject:@"user"]) {
            [[User sharedUser] setValuesForKeysWithDictionary:[successDic objectForKey:@"user"]];
            [Utility setObject:[User sharedUser] key:kUser];
            [Utility setObject:[User sharedUser].userId key:kUserId];
        }
        [self.navigationController popViewControllerAnimated:true];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        if ([[failData allKeys]containsObject:@"code"]) {
            if ([[NSString stringWithFormat:@"%@",[failData objectForKey:@"code"]]isEqualToString:@"200000"] ) {
                [TSMessage showNotificationInViewController:self title:@"验证码错误!" subtitle:@"请输入正确的验证码" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
            }
        } else {
            [TSMessage showNotificationInViewController:self title:@"修改失败!" subtitle:@"请稍后重试" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        }
        [self.navigationController popViewControllerAnimated:true];
    }];
}

@end
